class Line {
  #p0 = null;
  #color = "#000000";

  /**
   * 构造函数
   * @param {{x:Number, y:Number}} point
   */
  constructor(point) {
    this.#p0 = point;
  }

  #test = () => {
    window.console.log(this.#p0, this.#color);
  };

  /**
   * 设置颜色
   * @param {{x:Number, y:Number}} point
   */
  setColor = (color) => {
    this.#color = color;
  };

  /**
   * 设置起始点
   * @param {{x:Number, y:Number}} point
   */
  moveTo = (point) => {
    this.#test();
    this.#p0 = point;
    this.#test();
  };

  #drawDot = (img, p, canvasWidth) => {
    const pp = (p.x + canvasWidth * p.y) * 4;
    img.data[pp] = 255;
    img.data[pp + 3] = 255;
  };

  /**
   * 绘制直线
   * @param {{x:Number, y:Number}} point
   */
  lineTo(point, img, canvasWidth) {
    let P1 = point;
    let P0 = this.#p0;
    let p, t;
    if (Math.abs(P0.x - P1.x) < 1e-6) {
      if (P0.y > P1.y) {
        t = P0;
        P0 = P1;
        P1 = t;
      }
      for (p = P0; p.y < P1.y; p.y++) {
        this.#drawDot(img, p, canvasWidth);
      }
    } else {
      let k, d;
      k = (P1.y - P0.y) / (P1.x - P0.x);
      if (k > 1.0) {
        if (P0.y > P1.y) {
          t = P0;
          P0 = P1;
          P1 = t;
        }
        d = 1 - 0.5 * k;
        for (p = P0; p.y < P1.y; p.y++) {
          this.#drawDot(img, p, canvasWidth);
          if (d >= 0) {
            p.x++;
            d += 1 - k;
          } else d += 1;
        }
      }
      if (0.0 <= k && k <= 1.0) {
        if (P0.x > P1.x) {
          t = P0;
          P0 = P1;
          P1 = t;
        }
        d = 0.5 - k;
        for (p = P0; p.x < P1.x; p.x++) {
          this.#drawDot(img, p, canvasWidth);
          if (d < 0) {
            p.y++;
            d += 1 - k;
          } else d -= k;
        }
      }
      if (k >= -1.0 && k < 0.0) {
        if (P0.x > P1.x) {
          t = P0;
          P0 = P1;
          P1 = t;
        }
        d = -0.5 - k;
        for (p = P0; p.x < P1.x; p.x++) {
          this.#drawDot(img, p, canvasWidth);
          if (d > 0) {
            p.y--;
            d -= 1 + k;
          } else d -= k;
        }
      }
      if (k < -1.0) {
        if (P0.y < P1.y) {
          t = P0;
          P0 = P1;
          P1 = t;
        }
        d = -1 - 0.5 * k;
        for (p = P0; p.y > P1.y; p.y--) {
          this.#drawDot(img, p, canvasWidth);
          if (d < 0) {
            p.x++;
            d -= 1 + k;
          } else d -= 1;
        }
      }
    }
    // P0 = P1;
  }
}

export default Line;
